package com.learning.servlet2x.filter.gzip;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

/**
 * ClassName: GzipResponseWrapper
 * Description: 自定义的压缩流，内部调用JDK自带的压缩流
 * Date: 2014-12-9 21:41 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class GzipOutputStream extends ServletOutputStream {

    private HttpServletResponse response;

    /**
     * JDK 自带的压缩数据的类
     */
    private GZIPOutputStream gzipOutputStream;

    /**
     * 将压缩后的数据存放到 ByteArrayOutputStream 对象中
     */
    private ByteArrayOutputStream byteArrayOutputStream;

    public GzipOutputStream(HttpServletResponse response) throws IOException {
        this.response = response;
        byteArrayOutputStream = new ByteArrayOutputStream();
        gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
    }

    @Override
    public void write(int b) throws IOException {
        gzipOutputStream.write(b);
    }

    @Override
    public void close() throws IOException {

        // 压缩完毕 一定要调用该方法
        gzipOutputStream.finish();

        // 将压缩后的数据输出到客户端
        byte[] content = byteArrayOutputStream.toByteArray();

        // 设定压缩方式为 GZIP, 客户端浏览器会自动将数据解压
        response.addHeader("Content-Encoding", "gzip");
        response.addHeader("Content-Length", Integer.toString(content.length));

        // 输出
        ServletOutputStream out = response.getOutputStream();
        out.write(content);
        out.close();
    }

    @Override
    public void flush() throws IOException {
        gzipOutputStream.flush();
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        gzipOutputStream.write(b, off, len);
    }

    @Override
    public void write(byte[] b) throws IOException {
        gzipOutputStream.write(b);
    }
}
